package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/department")
public class DepartmentController {
    
    @Autowired
    private IDepartmentService departmentService;

    // 提供一个方法处理查询所有部门数据请求，响应 HTML
    @RequestMapping("/list")
    @RequiresPermissions(value = {"department:list","部门删除"},logical = Logical.OR)
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
        PageInfo pageInfo = departmentService.query(qo);
        //分页信息存入session
        model.addAttribute("result", pageInfo);
        return "department/list"; // /WEB-INF/views/department/list.ftl
    }

    @RequestMapping("/input")
    @RequiresPermissions(value = {"department:input","部门编辑"},logical = Logical.OR)
    public String input(Long id, Model model){
        if(id != null){ // 点击了修改按钮过来
            Department department = departmentService.get(id);
            model.addAttribute("department", department);
        }
        return "department/input"; // /WEB-INF/views/department/input.ftl
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"department:saveOrUpdate","部门保存或更新"},logical = Logical.OR)
    public JsonResult saveOrUpdate(Department department){
        try{
            if(department.getId() == null){
                departmentService.save(department);
            }else{
                departmentService.update(department);
            }
            return  new JsonResult(true,"修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = {"department:delete","部门删除"},logical = Logical.OR)
    public JsonResult delete(Long id){
        if (id != null) {
            departmentService.delete(id);
           return new JsonResult(true,"删除成功");
        }
        return new JsonResult(true,"删除失败");
    }
}
